package gpsm2

import (
	"crypto"
	"crypto/x509/pkix"
	"github.com/tjfoc/gmsm/sm3"
	"github.com/tjfoc/gmsm/sm4"
	"github.com/tjfoc/gmsm/x509"
	"syscall"
)


const SM2WithSM3 x509.SignatureAlgorithm = 16

func generateSymmKey(magic, pin, salt string) (key []byte) {

	hw := sm3.New()
	hw.Write([]byte(magic + pin + salt))
	key = hw.Sum(nil)[8:24]
	return
}

func symmEcbDecrypt(key, ciphertext, plaintext []byte) (err error) {
	n := len(ciphertext)
	if len(key) != 16 || (n&0xf) != 0 || n != len(plaintext) {
		err = syscall.EINVAL
		return
	}
	block, err := sm4.NewCipher(key)
	if err != nil {
		return err
	}
	n >>= 4
	for i := 0; i < n; i++ {
		block.Decrypt(plaintext[i*16:i*16+16], ciphertext[i*16:i*16+16])
	}
	return nil
}
func symmEcbEncrypt(key, plaintext, ciphertext []byte) (err error) {
	n := len(plaintext)
	if len(key) != 16 || (n&0xf) != 0 || len(ciphertext) != n {
		err = syscall.EINVAL
		return
	}
	block, err := sm4.NewCipher(key)
	if err != nil {
		return err
	}
	n >>= 4
	for i := 0; i < n; i++ {
		block.Encrypt(ciphertext[i*16:i*16+16], plaintext[i*16:i*16+16])
	}
	return nil
}
func GeneratePKCS10(signer crypto.Signer, name string) (csr []byte, err error) {
	tempCsr := x509.CertificateRequest{
		Subject: pkix.Name{
			CommonName:           name,
			// Organization:       []string{subject.Company},
			// OrganizationalUnit: []string{subject.Unit},
			// Locality:           []string{subject.City},
			// Province:           []string{subject.Province},
			// Country:            []string{subject.Country},
		},
		SignatureAlgorithm: SM2WithSM3,
	}

	csr, err = x509.CreateCertificateRequestToPem(&tempCsr, signer)
	return
}

